package com.cskaoyan.service;

import com.cskaoyan.bean.Permission;
import com.cskaoyan.bean.PermissionExample;
import com.cskaoyan.bean.sysmanage.InsertPermissionBo;
import com.cskaoyan.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    PermissionMapper permissionMapper;

    @Override
    public boolean updatePermission(InsertPermissionBo insertPermissionBo) {
        Integer roleId = insertPermissionBo.getRoleId();
        //先根据roleId删除所有权限，再插入对应的权限
        PermissionExample permissionExample = new PermissionExample();
        PermissionExample.Criteria criteria = permissionExample.createCriteria();
        if(roleId != null){
            criteria.andRoleIdEqualTo(roleId);
        }
        permissionMapper.deleteByExample(permissionExample);

        //再插入数据
        List<String> permissions = insertPermissionBo.getPermissions();
        if(permissions != null && permissions.size() > 0){
            for (String permission : permissions) {
                Permission insertPermission = new Permission();
                insertPermission.setRoleId(roleId);
                insertPermission.setPermission(permission);
                insertPermission.setAddTime(new Date());
                insertPermission.setUpdateTime(new Date());
                int insertRows = permissionMapper.insertSelective(insertPermission);
                if(insertRows == 0) return false;
            }
        }

        return true;
    }
}
